#!/usr/bin/env python3
# _*_ coding:utf-8 _*_

# from django.db.models import Q
# from django.utils.safestring import mark_safe
from django.shortcuts import HttpResponse, reverse, render, redirect
from rbac import models
from rbac.forms import User
from Arc.utils.GetData import getpage


# def data_serialize(row):
#     label = {
#         0: ' ',
#         1: 'label-success',
#         5: 'label-warning',
#         10: 'label-info',
#         -1: 'label-danger',
#     }
#     code_num = row.status
#     code_str = row.get_status_display()
#
#     text = '<span class="label  %s"><strong>&nbsp;&nbsp;%s&nbsp;&nbsp;</strong></span>' % (
#         label[code_num], code_str)
#
#     return text


def index(request):
    return render(request, 'rbac/index.html')


def user_list(request):
    user_queryset = models.User.objects.all()
    pager, data_list = getpage(request, user_queryset)
    return render(request, 'rbac/user_list.html', {'users': data_list, 'pager': pager})


def user_add(request):
    if request.method == 'POST':
        forms = User.UserModelForm(request.POST)
        if forms.is_valid():
            forms.save()
            return redirect('rbac:users')
    elif request.method == 'GET':
        forms = User.UserModelForm()
    else:
        forms = User.UserModelForm()
    return render(request, 'rbac/form_temp.html', {'forms': forms, })


def user_edit(request, pk):
    user_obj = models.User.objects.filter(id=pk).first()
    if not user_obj:
        return render(request, '404.html', {'error': '查看的用户不存在！'})
    if request.method == 'GET':
        forms = User.UpdateUserModelForm(instance=user_obj)
        return render(request, 'rbac/form_temp.html', {'forms': forms, })
    form = User.UpdateUserModelForm(instance=user_obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('rbac:users')
    else:
        return render(request, 'rbac/form_temp.html', {'forms': form})


def user_del(request, pk):
    if request.method == 'POST':
        if pk == request.POST.get('pk') and request.POST.get('csrfmiddlewaretoken'):
            models.User.objects.filter(id=pk).delete()
            return HttpResponse('200')
    else:
        return render(request, '403.html')


def change_passwd(request):
    pk = request.session['ID']
    user_obj = models.User.objects.filter(id=pk).first()
    if not user_obj:
        return render(request, '404.html', {'error': '查看的用户不存在！'})
    if request.method == 'GET':
        forms = User.ResetPasswordUserModelForm(instance=user_obj)
        return render(request, 'rbac/form_temp.html', {'forms': forms, })
    form = User.ResetPasswordUserModelForm(instance=user_obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('index_0')
    else:
        return render(request, 'rbac/form_temp.html', {'forms': form})
